package com.itheima.health.config;

import com.itheima.health.interceptor.AuthorityInterceptor;
import com.itheima.health.interceptor.LoginInterceptor;
import com.itheima.health.properties.AuthorityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置运行所有的请求跨域
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Autowired
    private AuthorityProperties authorityProperties;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")// 针对所有的请求
            .allowedOrigins("*")    // 允许来自所有的域
            .allowedMethods("*")    // 允许所有的HTTP Method
            .allowCredentials(true);// 允许携带cookie
    }

    /**
     * 通过拦截器来实现权限控制
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //第一个拦截用户是否登录
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns("/mobile/**","/user/login")
                .addPathPatterns("/**");

        //第二个拦截用户是否具有权限
        //需要拦截的有页面资源和操作请求，分别对应menus和permission的权限
        //menu资源前端没有实现，所以只需要拦截permission的权限
        registry.addInterceptor(new AuthorityInterceptor(authorityProperties))
                .excludePathPatterns("/mobile/**","/user/login")
                .addPathPatterns("/**");
    }
}